package cn.edu.klmy.controller;

import cn.edu.klmy.controller.importdata.ExcelMapperTeacher;
import cn.edu.klmy.controller.importdata.ImportError;
import cn.edu.klmy.dao.*;
import cn.edu.klmy.models.clasz.Clasz;
import cn.edu.klmy.models.teacher.Teacher;
import cn.edu.klmy.models.user.UserType;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import web.models.BatchSaveResult;
import web.models.CommonResult;
import web.models.Page;
import web.util.ExcelReader;
import web.util.FileUtil;
import web.util.RequestUtil;
import web.util.DaoUtil.SqlOperator;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/teacher")
public class TeacherController {
    @Resource(name = "teacherDao")
    private ITeacherDao teacherDao;
    @Resource(name = "accountDao")
    private IAccountDao accountDao;
    @Resource(name = "authorityDao")
    private IAuthorityDao authorityDao;
    @Resource(name = "claszDao")
    private IClaszDao claszDao;
    @Resource(name = "teacherClaszRelDao")
    private ITeacherClaszRelDao teacherClaszRelDao;
    private String tempPicturePath;
    private File picturePath;

    public TeacherController() {
        // 获取文件上传的地址
        String p = null;
        try {
            p = this.getClass().getClassLoader().getResource("").toURI().getPath();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        tempPicturePath = p.substring(1, p.lastIndexOf("WEB-INF/classes/")) + "upload/";
        picturePath = new File(tempPicturePath);
        if (!picturePath.exists()) {
            picturePath.mkdir();
        }
    }

    private File getPictureFile(String jsessionid) {
        //顾伟2013-8-26，解决目录找不到时会报空指针错误
        if (!picturePath.exists()) {
            picturePath.mkdir();
        }
        File[] tempFile = picturePath.listFiles();
        for (int i = 0; i < tempFile.length; i++) {
            System.out.println(tempFile[i].getName());
            if (tempFile[i].getName().startsWith(jsessionid)) {
                return tempFile[i];
            }
        }
        return null;
    }

    private void setTeacherPicture(String jsessionid, int teacherId) {
        File f = getPictureFile(jsessionid);
        if (null != f) {
            ByteArrayOutputStream pictureOs = new ByteArrayOutputStream();
            try {
                FileCopyUtils.copy(new FileInputStream(f), pictureOs);
            } catch (Exception e) {
                throw new RuntimeException(e.getLocalizedMessage());
            }
            teacherDao.setTeacherPicture(teacherId, pictureOs.toByteArray());
            f.delete();
        }
    }

    @RequestMapping("/add")
    @ResponseBody
    public CommonResult addTeacher(@ModelAttribute Teacher teacher, @CookieValue String JSESSIONID) {
        //增加老师
        teacherDao.addTeacher(teacher);
        //增加老师照片
        int teacherId = teacherDao.getTeacher("TEACHER_ID_NO", "'" + teacher.getIdentityCardNumber() + "'").getId();
        setTeacherPicture(JSESSIONID, teacherId);
        //增加登录账户
        accountDao.addAccount(teacher.getIdentityCardNumber(), teacher.getName(), UserType.Teacher.getMark());
        //增加登录老师的默认权限
        //int userId = accountDao.getAccountId(teacher.getIdentityCardNumber());
        //authorityDao.addDefaultPermission(userId);
        return new CommonResult(new Integer(teacherId));
    }

    public void addTeacher(Teacher teacher) {
        teacherDao.addTeacher(teacher);
        accountDao.addAccount(teacher.getIdentityCardNumber(), teacher.getName(), UserType.Teacher.getMark());
    }

    @RequestMapping("/{jsessionid}/picture")
    @ResponseBody
    public CommonResult uploadTempPicture(@PathVariable String jsessionid, @RequestParam MultipartFile picture) {
        // 删除旧的临时照片
//        String tempStr = jsessionid.substring(0,jsessionid.indexOf("-"));
        FileUtil.delFilesByNameStartWith(tempPicturePath, jsessionid);
        String fileName = picture.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        File f = new File(tempPicturePath + jsessionid + suffix);
        try {
            FileCopyUtils.copy(picture.getBytes(), f);
        } catch (Exception e) {
            throw new RuntimeException(e.getLocalizedMessage());
        }
        return new CommonResult(new Boolean(true));
    }

    @RequestMapping("/update")
    @ResponseBody
    public CommonResult updateTeacher(@ModelAttribute Teacher teacher, @CookieValue String JSESSIONID) {
        // 考虑更新身份证号号的问题
        Teacher oldTeacher = teacherDao.getTeacher("id", teacher.getId());
        if (!oldTeacher.getIdentityCardNumber().equals(teacher.getIdentityCardNumber())) {
            accountDao.changeAccountIdentityCardNumber(oldTeacher.getIdentityCardNumber(), teacher.getIdentityCardNumber());
        }
        if(teacher.getGrade().equals("0"))
            teacher.setGrade(null);
        if(teacher.getSubject().equals("0"))
            teacher.setSubject(null);

        teacherDao.updateTeacher(teacher);
        setTeacherPicture(JSESSIONID, teacher.getId());
        return new CommonResult(new Boolean(true));
    }

    @RequestMapping("/remove")
    @ResponseBody
    public CommonResult removeTeacher(@RequestParam int teacherId) {
        Teacher teacher = teacherDao.getTeacher("id", teacherId);
        if (teacher != null) {
            //删除权限
            //int userId = accountDao.getAccountId(teacher.getIdentityCardNumber());
            //authorityDao.removeUserPermissions(userId);
            //删除登录账户
            accountDao.removeAccount(teacher.getIdentityCardNumber());
            //删除班级中的学生关联
            // teacherClaszRelDao.removeTeacherFromAllClasz(teacher.getId());
            //删除老师的课程安排，可以在DAO层实现
            //删除老师
            teacherDao.removeTeacher(teacherId);
        }
        return new CommonResult(new Boolean(true));
    }

    @RequestMapping("/{teacherId}")
    @ResponseBody
    public Teacher getTeacher(@RequestParam int teacherId) {
        return teacherDao.getTeacher("id", teacherId);
    }

    @RequestMapping("/idno/{identityCardNumber}")
    @ResponseBody
    public Teacher getTeacherByIdNo(@PathVariable String identityCardNumber) {
        return teacherDao.getTeacher("teacher_id_no", "'" + identityCardNumber + "'");
    }

    @RequestMapping("/exists")
    @ResponseBody
    public CommonResult teacherExists(@RequestParam String identityCardNumber) {
        boolean result = teacherDao.teacherExistsByIdentityCardNumber(identityCardNumber);
        return new CommonResult(new Boolean(result));
    }

    @RequestMapping("/all")
    @ResponseBody
    public Page<Teacher> getTeachersPage(@RequestParam int page, @RequestParam int rows) {
        final List<Teacher> teachers = teacherDao.getTeachers(null, page, rows);
        int count = teacherDao.getTeacherCount(null);
        return new Page(count, teachers);
    }

    // 此处显示了如何通过Spring MVC来通过字节流返回图像，图片
    @RequestMapping("/getTeacherPicture/{teacherId}")
    @ResponseBody
    public void getTeacherPicture(@PathVariable int teacherId, HttpServletRequest request,
                                  HttpServletResponse response) throws IOException {
        byte[] picture = teacherDao.getTeacherPicture(teacherId);
        if (null == picture)
            return;
        response.setContentType("image/JPG");
        OutputStream stream = response.getOutputStream();
        stream.write(picture);
        stream.flush();
        stream.close();
    }

    @RequestMapping(value = "/exportTeachers", method = RequestMethod.POST)
    @ResponseBody
    public BatchSaveResult<String> handleFormUpload(@RequestParam(value = "file") MultipartFile file) throws Exception {
        String fileName = null;
        if (!file.isEmpty()) {
            fileName = file.getOriginalFilename();
            ExcelMapperTeacher ems = new ExcelMapperTeacher();
            List teachers = ExcelReader.readExcel(file.getInputStream(), ems, fileName.toUpperCase().endsWith(".XLSX"));
            if (null != teachers && !teachers.isEmpty()) {
                BatchSaveResult<String> bsr = new BatchSaveResult<String>();
                bsr.setRecordCount(teachers.size());
                int sucessCount = 0;
                List<String> identityCardNumbers = new ArrayList<String>();
                List<String> validErrors = new ArrayList<String>();
                for (Object teacher : teachers) {
                    if (teacher == null)
                        continue;
                    try {
                        addTeacher((Teacher) teacher);
                    } catch (Throwable t) {
                        String e = "身份证号:[" + ((Teacher) teacher).getIdentityCardNumber() + "]";
                        if (!identityCardNumbers.contains(e)) {
                            identityCardNumbers.add(e);
                        }
                        continue;
                    }
                    sucessCount++;
                }
                if (ems.getImportErrors() != null && !ems.getImportErrors().isEmpty()) {
                    for (ImportError e : ems.getImportErrors()) {
                        if (e.getType() == 0) {
                            validErrors.add("所在行:[" + (e.getRow().getRowNum() + 1) + "] 信息:[" + e.getError() + "]");
                        } else {
                            validErrors.add("所在行:[" + (e.getRow().getRowNum() + 1) + "] 信息:[" + e.getError() + "]");
                        }
                    }
                }
                bsr.setSucessCount(sucessCount);
                bsr.setFailInfo(identityCardNumbers);
                bsr.setValidInfo(validErrors);
                return bsr;
            }
        }
        return null;
    }

    @RequestMapping("/list/all")
    @ResponseBody
    public List<Teacher> getAllTeachers() {
        return teacherDao.getAllTeachers();
    }

    @RequestMapping("/{teacherId}/all-claszs")
    @ResponseBody
    public List<Clasz> getClaszsOfTecher(@PathVariable int teacherId) {
        return claszDao.getClaszsOfTeacher(teacherId);
    }

    @RequestMapping("/{teacherId}/all-notin-claszs")
    @ResponseBody
    public List<Clasz> getClaszsNotOfTeacher(@PathVariable int teacherId) {
        return claszDao.getClaszsNotOfTeacher(teacherId);
    }

    @RequestMapping("/{teacherId}/all-notin-claszs-byname")
    @ResponseBody
    public List<Clasz> getClaszsNotOfTeacherSearchByName(@PathVariable int teacherId, @RequestParam String name) {
        List<Clasz> notOfClaszs = claszDao.getClaszsNotOfTeacher(teacherId);
        List<Clasz> result = new ArrayList<Clasz>();
        if (null != notOfClaszs) {
            for (Clasz clasz : notOfClaszs) {
                if (clasz.getName().contains(name)) {
                    result.add(clasz);
                }
            }
        }
        return result;
    }

    @RequestMapping("/{teacherId}/addclaszs")
    @ResponseBody
    public CommonResult addClaszsOfTeacher(@PathVariable int teacherId, @RequestParam String claszIdsStr) {
        int[] claszIds = RequestUtil.convertStrToIntArray(claszIdsStr);
        teacherClaszRelDao.addClaszsToTeacher(claszIds, teacherId);
        return new CommonResult(new Boolean(true));
    }

    @RequestMapping("/{teacherId}/removeclaszs")
    @ResponseBody
    public CommonResult removeClaszsOfTeacher(@PathVariable int teacherId, @RequestParam String claszIdsStr) {
        int[] claszIds = RequestUtil.convertStrToIntArray(claszIdsStr);
        teacherClaszRelDao.removeClaszsFromTeacher(claszIds, teacherId);
        return new CommonResult(new Boolean(true));
    }

    @RequestMapping(value = "/teacher-by-name", method = RequestMethod.POST)
    @ResponseBody
    public Page<Teacher> getTeachersPage(@RequestParam String name, @RequestParam int page, @RequestParam int rows) {
        return getTeachersByName(name, page, rows);
    }

    private Page<Teacher> getTeachersByName(String teacherName, int page, int rows) {
        Map<String, Object[]> params = new HashMap<String, Object[]>();
        params.put("teacher_name", new Object[]{ SqlOperator.like, teacherName });
        List<Teacher> teachers = teacherDao.getTeachers(params, page, rows);
        int count = teacherDao.getTeacherCount(params);
        return new Page<Teacher>(count, teachers);
    }

    public void setTeacherDao(ITeacherDao teacherDao) {
        this.teacherDao = teacherDao;
    }

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

}
